package com.woniuxy.microfundservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.microfundservice.bean.info.FundPosition;
import com.woniuxy.microfundservice.bean.info.FundPositionMsg;
import com.woniuxy.microfundservice.service.FundPositionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * (FundPosition)表控制层
 *
 * @author makejava
 * @since 2021-04-08 09:40:40
 */
@RefreshScope
@Api("基金持仓情况")
@RestController
@RequestMapping(value = "/fundPosition",produces = MediaType.APPLICATION_JSON_VALUE)
public class FundPositionController {
    /**
     * 服务对象
     */
    @Resource
    private FundPositionService fundPositionService;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 通过主键查询单条数据
     *
     * @param fundId 主键
     * @return 单条数据
     */
    @ApiOperation(("从数据库查找基金持仓"))
    @GetMapping("/selectlocal")
    public ResultBean selectLocal(Integer fundId) {

        FundPosition fundPosition=fundPositionService.selectLocal(fundId);
        return ResultBean.builder().code(200).data(fundPosition).build();
    }

    @ApiOperation(("在线查找基金持仓"))
    @GetMapping("/selectnet")
    public ResultBean selectNet(String fundCode) {


        HttpHeaders httpHeaders = new HttpHeaders();
        //定义传输的数据的数据方式
        //组装数据
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, httpHeaders);
        //外部接口的地址
        String url="https://api.doctorxiong.club/v1/fund/position?code="+fundCode;
        ResponseEntity<FundPositionMsg> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, FundPositionMsg.class);
        return ResultBean.builder().code(200).data(exchange.getBody().getData()).build();
    }

    //必须传入6位基金code
    @ApiOperation(("查找基金并存进数据库"))
    @GetMapping("/selectAdd")
    public ResultBean selectAdd(int fundCodeInt) {

        return fundPositionService.selectAdd(fundCodeInt);
    }

    @ApiOperation(("新增基金持仓"))
    @PostMapping("/addone")
    public ResultBean addOne(@RequestBody FundPosition fundPosition) {

        fundPositionService.addOne(fundPosition);
        return ResultBean.builder().code(200).data(fundPosition).build();
    }
}